import * as React from 'react';
import { Modal } from 'office-ui-fabric-react/lib/Modal';
import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/Button';
import { addParagraphs } from '../../utils/Paragraphs';
import { getResourceGuid } from '../../utils/WordUtil';
import { TextField, ChoiceGroup, IChoiceGroupOption } from 'office-ui-fabric-react';

export class BodyExample extends React.Component<
  {},
  {
    showModal: boolean,
    wordContent: any,
    type: string
  }
  > {
  constructor(props: {}) {
    super(props);
    this.state = {
      type: 'ooxml',
      showModal: false,
      wordContent: ''
    };
  }

  componentDidMount() {

  }


  public render() {
    const { wordContent, type } = this.state
    return (
      <div>
        <PrimaryButton secondaryText="Opens the insert paragraphs Sample Dialog" onClick={this._showDialog} text="选择Body" />
        <Modal
          isOpen={this.state.showModal}
          onDismiss={this._closeDialog}
          isBlocking={false}
          containerClassName="ms-modalExample-container"
        >
          <ChoiceGroup
            selectedKey={type}
            options={[
              {
                key: 'text',
                text: 'text',
                'data-automation-id': 'auto1'
              } as IChoiceGroupOption,
              {
                key: 'html',
                text: 'html'
              },
              {
                key: 'ooxml',
                text: 'ooxml',
              },
            ]}
            onChange={this.onTypeChange}
            label="Pick one"
            required={true}
          />
          <div>
            <DefaultButton onClick={this.click}>关闭</DefaultButton>
            <DefaultButton onClick={this.openDialog}>外部弹窗</DefaultButton>
            <DefaultButton onClick={this.addParagraphs}>添加</DefaultButton>
            <DefaultButton onClick={this.wordOoxml}>获取wordOoxml</DefaultButton>
            <DefaultButton onClick={this.content}>获取word内容</DefaultButton>
            <DefaultButton onClick={this.getFirstParagraph}>获取第一段</DefaultButton>
            <DefaultButton onClick={this.replace}>替换word内容</DefaultButton>
            <DefaultButton onClick={this.hightlightLongestWord}>选中搜索最长的高亮</DefaultButton>
          </div>

          <br />
          <TextField label="With auto adjusting height" value={wordContent} onChange={this.textChange} multiline resizable />
          显示源码：
          <br />
          <div>

            <div dangerouslySetInnerHTML={{ __html: wordContent }}>

            </div>
          </div>

        </Modal>
      </div>
    );
  }


  private onTypeChange = (ev: React.FormEvent<HTMLInputElement>, option: any): void => {
    console.dir(option);
    this.setState({
      type: option.key
    })
  };
  private textChange = (ev, value) => {
    this.setState({
      wordContent: value
    })
  }
  private getFirstParagraph = () => {
    getResourceGuid() // 测试方法能不能用
    this.getParagraphs().then(
      res => {
        this.setState({
          wordContent: res
        })
      }
    )
  }
  private content = () => {
    this.getWordContent().then(
      res => {
        this.setState({
          wordContent: res
        })
      }
    )
  }
  private wordOoxml = () => {
    this.getWordOoxml().then(
      res => {
        this.setState({
          wordContent: res
        })
      }
    )
  }

  private replace = () => {
    const { wordContent } = this.state
    this.replaceWordContent(wordContent)
  }

  private addParagraphs = async () => {
    addParagraphs()
  }

  openDialog = () => {
    Office.context.ui.displayDialogAsync('https://www.baidu.com', { width: 300, height: 200 },
      function (result) {
        // dialog = result.value;
        // dialog.addEventHandler(Office.EventType.DialogEventReceived, processDialogEvent);
      }
    );
  }

  private click = async () => {
    this.setState({ showModal: false });

    console.log("Body 点击方法");
    this.getDocument()

    // 修改颜色
    // return Word.run(async context => {

    //   var body = context.document.body;
    //   body.insertBreak(Word.BreakType.page, Word.InsertLocation.end);

    //   const range = context.document.getSelection();

    //   // Read the range text
    //   range.load('text');

    //   // Update font color
    //   range.font.color = 'red';

    //   await context.sync();
    //   console.log(`The selected text was ${range.text}.`);
    // });
  }
  private _showDialog = (): void => {

    // Run a batch operation against the Word object model.
    Word.run(function (context) {

      // Create a proxy sectionsCollection object.
      var mySections = context.document.sections;

      // Queue a commmand to load the sections.
      context.load(mySections, 'body/style');

      // Synchronize the document state by executing the queued commands,
      // and return a promise to indicate task completion.
      return context.sync().then(function () {

        // Create a proxy object the primary header of the first section.
        // Note that the header is a body object.
        var myHeader = mySections.items[0].getHeader("primary");

        // Queue a command to insert text at the end of the header.
        myHeader.insertText("This is a header.", Word.InsertLocation.end);

        // Queue a command to wrap the header in a content control.
        myHeader.insertContentControl();

        // Synchronize the document state by executing the queued commands,
        // and return a promise to indicate task completion.
        return context.sync().then(function () {
          console.log("Added a header to the first section.");
        });
      });
    })
      .catch(function (error) {
        console.log('Error: ' + JSON.stringify(error));
        if (error instanceof OfficeExtension.Error) {
          console.log('Debug info: ' + JSON.stringify(error.debugInfo));
        }
      });

    this.setState({ showModal: true });

    // 打开弹窗选择全部

    // Run a batch operation against the Word object model.
    Word.run(function (context) {

      // Create a proxy object for the document body.
      var section = context.document.getSelection();
      context.load(section, 'text')
      // Create a proxy object for the document body.
      var body = context.document.body;

      // Queue a commmand to select the document body. The Word UI will
      // move to the selected document body.
      body.select();

      // Synchronize the document state by executing the queued commands,
      // and return a promise to indicate task completion.
      return context.sync().then(function () {
        console.log('getSelecTion', section)
        console.log('getSelecTion text', section.text)
        console.log('Selected the document body2.', body.toJSON());
      });
    }).catch(function (error) {
      console.log('Error: ' + JSON.stringify(error));
      if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
      }
    });
  };

  private _closeDialog = (): void => {
    this.setState({ showModal: false });
  };


  // 测试document 对象
  getDocument = () => {
    console.log("测试document 对象");
    // Run a batch operation against the Word object model.
    Word.run(function (context) {
      // Create a proxy object for the document.
      var thisDocument = context.document;

      // Queue a command to load content control properties.
      context.load(thisDocument, 'contentControls/id, contentControls/text, contentControls/tag');

      // Synchronize the document state by executing the queued commands,
      // and return a promise to indicate task completion.
      return context.sync().then(function () {
        if (thisDocument.contentControls.items.length !== 0) {
          for (var i = 0; i < thisDocument.contentControls.items.length; i++) {
            console.log(thisDocument.contentControls.items[i].id);
            console.log(thisDocument.contentControls.items[i].text);
            console.log(thisDocument.contentControls.items[i].tag);
          }
        } else {
          console.log('No content controls in this document.');
        }
      });
    })
      .catch(function (error) {
        console.log('Error: ' + JSON.stringify(error));
        if (error instanceof OfficeExtension.Error) {
          console.log('Debug info: ' + JSON.stringify(error.debugInfo));
        }
      });
  }





  private hightlightLongestWord = () => {
    Word.run(function (context) {
      // Queue a command to get the current selection and then
      // create a proxy range object with the results.
      var range = context.document.getSelection();

      // This variable will keep the search results for the longest word.
      var searchResults;
      var searchResults2;

      // Queue a command to load the range selection result.
      context.load(range, 'text');

      // Synchronize the document state by executing the queued commands
      // and return a promise to indicate task completion.
      return context.sync()
        .then(function () {
          // Get the longest word from the selection.
          var words = range.text.split(/\s+/);
          var longestWord = words.reduce(function (word1, word2) { return word1.length > word2.length ? word1 : word2; });

          // Queue a search command.
          // searchResults = range.search(longestWord, { matchCase: true, matchWholeWord: true });
          searchResults = range.search('关键词1|关键词3', { matchWildcards: true });

          // Queue a commmand to load the font property of the results.
          context.load(searchResults, 'font');

          // searchResults2 = range.search('关键词2', { ignorePunct: true });
          // context.load(searchResults2, 'font');
        })
        .then(context.sync)
        .then(function () {
          console.info('最长的词 items', searchResults.items)
          console.info('关键词2', searchResults2.items)

          searchResults2.items[0].font.highlightColor = '#FFF000';

          // Queue a command to highlight the search results.
          searchResults.items[0].font.highlightColor = '#FFF000'; // Yellow
          searchResults.items[0].font.bold = true;
          let contentControl = searchResults.items[0].insertContentControl()
          contentControl.cannotEdit = true;
          contentControl.appearance = "Tags";

          if (searchResults.items.length < 1) return;
          searchResults.items[1].font.bold = true;
          searchResults.items[1].insertContentControl().appearance = "Tags";
        })
        .then(context.sync);
    })
    // .catch(errorHandler);
  }

  getParagraphs() {
    return Word.run(function (context) {

      // Create a proxy object for the paragraphs collection.
      var paragraphs = context.document.body.paragraphs;

      // Queue a commmand to load the text property for all of the paragraphs.
      context.load(paragraphs, 'text');

      // Synchronize the document state by executing the queued commands,
      // and return a promise to indicate task completion.
      return context.sync().then(function () {

        // Queue a a set of commands to get the HTML of the first paragraph.
        var html = paragraphs.items[0].getHtml();

        // Synchronize the document state by executing the queued commands,
        // and return a promise to indicate task completion.
        return context.sync().then(function () {
          console.log('Paragraph HTML: ' + html.value);
          return html.value
        });
      });
    })
      .catch(function (error) {
        console.log('Error: ' + JSON.stringify(error));
        if (error instanceof OfficeExtension.Error) {
          console.log('Debug info: ' + JSON.stringify(error.debugInfo));
        }
      });
  }
  /**
   * get the ooxml of the doc
   *
   *
   * @memberOf WordDocumentService
   */
  getWordOoxml() {
    // Run a batch operation against the Word object model.
    return Word.run(function (context) {

      var body = context.document.body;

      var wordContent = body.getOoxml();

      return context.sync().then(function () {
        console.log("Body contents: " + wordContent.value);
        return wordContent.value;
      });
    }).catch(function (error) {
      console.log("Error: " + JSON.stringify(error));
      if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
      }
      return "";
    });
  }
  getWordContent = () => {
    // Run a batch operation against the Word object model.
    const { type } = this.state
    return Word.run(function (context) {

      var body = context.document.body;
      context.load(body, 'text')
      var wordContent = body.getHtml();

      // switch (type) {
      //   case 'html':
      //     wordContent = body.getHtml();
      //   case 'ooxml':
      //     wordContent = body.getOoxml();
      // }

      return context.sync().then(function () {
        console.log("Body contents: ", body.text);
        return wordContent.value;
      });
    }).catch(function (error) {
      console.log("Error: " + JSON.stringify(error));
      if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
      }
      return "";
    });
  }

  /**
   * set the ooxml of the doc
   *
   * @param {string} ooxml
   *
   * @memberOf WordDocumentService
   */
  public replaceWordContent = (ooxml: string) => {
    const { type } = this.state
    console.log('开始.', type, ooxml);
    // Run a batch operation against the Word object model.
    Word.run(function (context) {

      console.log('插入.');
      var body = context.document.body;

      switch (type) {
        case 'text':
          body.insertText(ooxml, Word.InsertLocation.end);
        case 'html':
          body.insertHtml(ooxml, Word.InsertLocation.end);
        case 'ooxml':
          body.insertOoxml(ooxml, Word.InsertLocation.end);
      }

      return context.sync().then(function () {
        console.log('OOXML added to the beginning of the document body.');
      });
    })
      .catch(function (error) {
        console.log('Error: ' + JSON.stringify(error));
        if (error instanceof OfficeExtension.Error) {
          console.log('Debug info: ' + JSON.stringify(error.debugInfo));
        }
      });
  }

  insertHTML() {
    Word.run(function (context) {
      const blankParagraph = context.document.body.paragraphs.getLast().insertParagraph("", "After");
      blankParagraph.insertHtml('<p style="font-family: verdana;">Inserted HTML.</p><p>Another paragraph</p>', "End");

      return context.sync();
    }).catch(function (error) {
      console.log('Error:' + error);
      if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
      }
    });
  }
}

export default BodyExample
